package com.shenma2009.filter;

import com.alibaba.fastjson2.JSON;
import com.shenma2009.domain.ResultResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author 军哥
 * @version 1.0
 * @description: GatewayFilter
 * @date 2023/4/20 15:45
 */
@Configuration
public class GatewayFilter implements GlobalFilter, Ordered {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取Request、Response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 解决中文乱码问题
        HttpHeaders headers = response.getHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 打印输出URI:白名单
        String requestUrl = exchange.getRequest().getURI().getRawPath();
        System.out.println(requestUrl);
        System.out.println(request.getURI());
        if(requestUrl.contains("/login")) {
            return chain.filter(exchange);
        }
        if(requestUrl.contains("/upload")) {
            return chain.filter(exchange);
        }

        // 检查token
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)) {

            ResultResponse resultResponse = ResultResponse.FAILED(401, "缺少token");
            String msg = JSON.toJSONString(resultResponse);

            DataBuffer dataBuffer = response.bufferFactory().wrap(msg.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }

        // 检查token是否合法
        Boolean hasKey = redisTemplate.hasKey(token);
        if(!hasKey) {
            ResultResponse resultResponse = ResultResponse.FAILED(401, "token失效");
            String msg = JSON.toJSONString(resultResponse);

            DataBuffer dataBuffer = response.bufferFactory().wrap(msg.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }

        // token续期
        redisTemplate.expire(token, 10, TimeUnit.MINUTES);

        // 放行
        return chain.filter(exchange);
    }

    /**
     * @description 数字越小优先级越高
     * @author 军哥
     * @date 2023/4/20 15:46
     * @version 1.0
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
